/**
 * ERP集成规则控制类
 * 
 * @author 魏文杰 
 * @Version 1.0
 * @Date 2013-10-08
 */

package ext.generic.erp.rule;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

import wt.access.AccessControlHelper;
import wt.access.AccessPermission;
import wt.fc.PersistenceHelper;
import wt.inf.container.WTContainer;
import wt.inf.team.ContainerTeam;
import wt.inf.team.ContainerTeamHelper;
import wt.inf.team.ContainerTeamManaged;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTOrganization;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.part.WTPart;
import wt.project.Role;
import wt.session.SessionHelper;
import wt.util.WTException;
import ext.com.org.OrgUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.generic.erp.util.BusinessRuleXMLConfigUtil;
import ext.generic.erp.util.IntegrationConstant;
import ext.generic.erp.util.PDMIntegrationLogUtil;

public class BussinessRule {
	private static String clazz = BussinessRule.class.getName() ;
	
	/**
	 * 判断零部件软类型是否可发布
	 * 
	 * @param part
	 * @return
	 */
	public static boolean canReleasePart(WTPart part) {
		boolean canReleasePart = true;

		try {
			if (part != null) {
				String softType = CommonPDMUtil.getSoftType(part);

				if (BusinessRuleXMLConfigUtil.getInstance().getNoReleasePartSoftTypeList().contains(softType)) {
					canReleasePart = false;
				}
			}
		} catch (WTException e) {
			e.printStackTrace();
		}
		return canReleasePart;
	}
	
	/**
	 * 是否启用数据备份功能
	 * 
	 * @return
	 */
	public static boolean startBackupData() {
		return BusinessRuleXMLConfigUtil.getInstance().isStartBackupData(); 
	}
	
	/**
	 * 是否发布全局替代关系
	 * 
	 * @return
	 */
	public static boolean isAlternateLinkRelease() {
		return BusinessRuleXMLConfigUtil.getInstance().isReleaseAlternateLink(); 
	}

	/**
	 * 判断当前用户是否可以查询价格信息
	 * 
	 * @return
	 */
	public static boolean canReadPrice() {
		boolean canReadPrice = false;
		
		try{			
			WTPrincipal currentPrincipal = SessionHelper.getPrincipal() ;
			
			WTOrganization wtorganization = OrganizationServicesHelper.manager.getOrganization(currentPrincipal);
			
			if( currentPrincipal != null ){
				boolean isGroupUser = isReadPriceGroupUser( currentPrincipal, wtorganization ) ;
				
				if( isGroupUser ){
					canReadPrice = true ;
				}
			}else{
				PDMIntegrationLogUtil.printLog(clazz, ">>>>>> currentPrincipal == NULL" , IntegrationConstant.LOG_LEVEL_ERROR ) ;
			}
		} catch (WTException e) {
			e.printStackTrace();
		}finally{
			
		}

		PDMIntegrationLogUtil.printLog(clazz, ">>>>>> canReadPrice = " + canReadPrice) ;
		
		return canReadPrice;
	}
	
	/**
	 * 判断当前Session的用户，是否为特殊用户组中的用户
	 * 
	 * @param currentPrincipal	当前Session中的Principal
	 * @param org	当前对象所属的组织
	 * @return
	 * @throws WTException
	 */
	private static boolean isReadPriceGroupUser( WTPrincipal currentPrincipal, WTOrganization org) throws WTException {	
		boolean isGroupUser = false ;
		
		if( org != null ){
			PDMIntegrationLogUtil.printLog(clazz, ">>>>>ReadPriceGroupUser Method , User Group Name is : " + org.getName() ) ;

			List<String> userGroup = BusinessRuleXMLConfigUtil.getInstance().getReadPriceUserGroup();
			
			Iterator<String> groupIte = userGroup.iterator() ;
			while( groupIte.hasNext()){
				String groupName = groupIte.next() ;
				
				WTGroup group = OrgUtil.getGroupByName( org , groupName );
				isGroupUser = isGroupUser(currentPrincipal , group);
				
				if( isGroupUser ){
					return isGroupUser ;
				}
			}
		}else{
			PDMIntegrationLogUtil.printLog(clazz, ">>>>>ReadPriceGroupUser Method , User Group is NULL" ) ;
		}
		
		return isGroupUser;
	}
	
	/**
	 * 判断当前用户，是否可以执行手工发布零部件信息到中间表的操作
	 * 
	 * @param part
	 * @return
	 */
	public static boolean showManuallyPublishMenu( WTPart part ){
		boolean result = false ;
		
		try {
			WTPrincipal principal = SessionHelper.getPrincipal() ;
			
			if( principal != null ){
				//如果当前用户为授权的角色，或者当前用户属于授权的组，或者当前用户对零部件具有管理权限
				if( isManuallyPublishAllowedRole( principal , part ) || isManuallyPublishAllowedUserGroup( principal , part ) || isManuallyPublishAllowedPermission( part ) ){
					
					//如果零部件处于允许发布至中间表的状态，并且为允许发布至中间表的视图
					if( isManuallyPublishAllowedState( part ) && isManuallyPublishAllowedView( part )){
						result = true ;
					}
				}
			}
		} catch (WTException e) {
			e.printStackTrace();
		}

		return result ;
	}
	
	/**
	 * 判断当前用户，是否为授权的角色
	 * 
	 * @param currentPrincipal
	 * @param part
	 * @return
	 * @throws WTException
	 */
	private static boolean isManuallyPublishAllowedRole( WTPrincipal currentPrincipal , WTPart part ) throws WTException{
		boolean isAllowedRole = false ;
		
		List<String> userRoleList = BusinessRuleXMLConfigUtil.getInstance().getManuallyPublishUserRole() ;
		
		WTContainer container = part.getContainer();
		
		if( container != null && container instanceof ContainerTeamManaged){
			ContainerTeamManaged containerTeamManaged = ( ContainerTeamManaged ) container ;
			
			ContainerTeam containerTeam = ContainerTeamHelper.service.getContainerTeam( containerTeamManaged );
			
			if( containerTeam != null ){
				Vector roles = containerTeam.getRoles();

				Iterator ite = roles.iterator() ;

				while(ite.hasNext()){
					Object roleObj = ite.next() ;
					
					if( roleObj != null && roleObj instanceof Role ){
						Role role = (Role) roleObj ;
						
						String roleName = role.getDisplay( Locale.CHINA ) ;
						
						PDMIntegrationLogUtil.printLog(clazz, "isManuallyPublishAllowedRole Method , 解析团队角色，角色名为：" + roleName ) ;

						if( userRoleList.contains( roleName )){
							Enumeration participants= containerTeam.getPrincipalTarget( role );
							
							isAllowedRole = hasCurrentPrincipal( participants , currentPrincipal );
							
							if( isAllowedRole ){
								PDMIntegrationLogUtil.printLog(clazz, ">>>>> isManuallyPublishAllowedRole : " + isAllowedRole ) ;

								return isAllowedRole ;
							}
						}
					}
				}
			}	
		}
		
		PDMIntegrationLogUtil.printLog(clazz, ">>>>> isManuallyPublishAllowedRole : " + isAllowedRole ) ;
		
		return isAllowedRole ;
	}

	/**
	 * 判断当前用户是否在集合中
	 * 
	 * @param participants
	 * @param currentPrincipal
	 * @return
	 * @throws WTException
	 */
	private static boolean hasCurrentPrincipal( Enumeration participants , WTPrincipal currentPrincipal ) throws WTException {
		boolean hasCurrentPrincipal = false ;
		
		WTPrincipal principal = null ;
		
		if( participants != null ){
			while( participants.hasMoreElements() ){
				Object obj = participants.nextElement() ;
				
				if( obj != null && obj instanceof WTPrincipal ){
					principal = ( WTPrincipal ) obj ;
				}else if( obj != null && obj instanceof WTPrincipalReference ){
					WTPrincipalReference wtprincipalReference = ( WTPrincipalReference ) obj ;
					principal = wtprincipalReference.getPrincipal() ;					
				}else{
					if( obj == null ){
						PDMIntegrationLogUtil.printLog(clazz, ">>>>> hasCurrentPrincipal , obj == null ", IntegrationConstant.LOG_LEVEL_WARN ) ;
					}else{
						PDMIntegrationLogUtil.printLog(clazz, ">>>>> hasCurrentPrincipal , obj class type is " + obj.getClass() , IntegrationConstant.LOG_LEVEL_WARN ) ;
					}
				}
				
				if( principal != null ){
					hasCurrentPrincipal = PersistenceHelper.isEquivalent( principal , currentPrincipal );
				}
				
				if( hasCurrentPrincipal ){
					return hasCurrentPrincipal ;
				}
			}
		}
		
		return hasCurrentPrincipal ;
	}
	
	/**
	 * 判断当前用户是否属于授权的用户组
	 * 
	 * @param currentPrincipal
	 * @param part
	 * @return
	 * @throws WTException
	 */
	private static boolean isManuallyPublishAllowedUserGroup( WTPrincipal currentPrincipal , WTPart part ) throws WTException{
		boolean isAllowedUserGroup = false ;
		
		WTOrganization org = CommonPDMUtil.getOrganization( part ) ;
		
		List<String> userGroupList = BusinessRuleXMLConfigUtil.getInstance().getManuallyPublishUserGroup() ;
		
		Iterator<String> groupIte = userGroupList.iterator() ;
		while( groupIte.hasNext()){
			String groupName = groupIte.next() ;
			
			WTGroup group = OrgUtil.getGroupByName( org , groupName );
			
			isAllowedUserGroup = isGroupUser(currentPrincipal , group);
			
			if( isAllowedUserGroup ){
				PDMIntegrationLogUtil.printLog(clazz, ">>>>> isManuallyPublishAllowedUserGroup : " + isAllowedUserGroup ) ;
				
				return isAllowedUserGroup ;
			}
		}
		
		PDMIntegrationLogUtil.printLog(clazz, ">>>>> isManuallyPublishAllowedUserGroup : " + isAllowedUserGroup ) ;
		
		return isAllowedUserGroup ;
	}
	
	/**
	 * 判断当前用户是否为零部件的管理者
	 * 
	 * @param part
	 * @return
	 * @throws WTException
	 */
	private static boolean isManuallyPublishAllowedPermission( WTPart part ) throws WTException{
		boolean isAllowedPermission = AccessControlHelper.manager.hasAccess( part ,AccessPermission.ADMINISTRATIVE);
		
		PDMIntegrationLogUtil.printLog(clazz, ">>>>> is Allowed Permission : " + isAllowedPermission ) ;
		
		return isAllowedPermission ;
	}
	
	/**
	 * 判断当前零部件是否为可发布至中间表的生命周期状态
	 * 
	 * @param part
	 * @return
	 * @throws WTException
	 */
	private static boolean isManuallyPublishAllowedState( WTPart part ) throws WTException{
		boolean isAllowedState = false ;
		
		List<String> partStateList = BusinessRuleXMLConfigUtil.getInstance().getManuallyPublishPartState() ;
		
		//如果包含ALL，则所有状态都可以发布
		if( partStateList.contains("ALL") ){
			isAllowedState = true ;
		}else{
			String lifecycleState = CommonPDMUtil.getLifecycleCN( part ) ;
			
			if( lifecycleState != null && partStateList.contains( lifecycleState ) ){
				isAllowedState = true ;
			}
		}
		
		PDMIntegrationLogUtil.printLog(clazz, ">>>>> is Allowed State : " + isAllowedState ) ;

		return isAllowedState ;
	}
	
	/**
	 * 判断零部件是否为可发布中间表的视图
	 * 
	 * @param part
	 * @return
	 */
	private static boolean isManuallyPublishAllowedView( WTPart part ){
		boolean isAllowedView = false ;
		
		List<String> partViewList = BusinessRuleXMLConfigUtil.getInstance().getManuallyPublishPartView() ;
		
		//如果包含ALL，则所有视图都可以发布
		if( partViewList.contains("ALL") ){
			isAllowedView = true ;
		}else{
			String partView = part.getViewName() ;
			
			if( partView != null && partViewList.contains(partView) ){
				isAllowedView = true ;
			}
		}
		
		PDMIntegrationLogUtil.printLog(clazz, ">>>>> is Allowed View : " + isAllowedView ) ;

		return isAllowedView ;
	}
	
	public static boolean isGroupUser(WTPrincipal currentPrincipal , WTGroup group) throws WTException {
		boolean isGroupUser = false ;
		
		if( group != null ){
			
			//获取组成员
			Enumeration members= group.members();
			while( members.hasMoreElements()) {
				Object userObj =  members.nextElement();
				
				if( userObj != null && userObj instanceof WTPrincipal ){
					WTPrincipal groupPrincipal = ( WTPrincipal ) userObj ;
					
					isGroupUser = PersistenceHelper.isEquivalent( groupPrincipal , currentPrincipal ) ;

					if( isGroupUser ){
						return isGroupUser ;
					}
				}
			}
		}
		
		PDMIntegrationLogUtil.printLog(clazz, ">>>>> isGroupUser Method , is Group User : " + isGroupUser ) ;
		
		return isGroupUser ;
	}
}
